/**
 * 动画效果模块
 * 处理页面中的各种动画效果
 */

/**
 * 初始化滚动动画
 * @param {Object} options - 配置选项
 * @param {string} options.selector - 要观察的元素选择器
 * @param {number} options.threshold - 交叉观察器阈值
 */
export function initScrollAnimations(options = {}) {
    const { 
        selector = '.animate-on-scroll', 
        threshold = 0.1 
    } = options;
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('visible');
                observer.unobserve(entry.target);
            }
        });
    }, {
        threshold: threshold
    });
    
    // 观察所有指定选择器的元素
    document.querySelectorAll(selector).forEach(element => {
        // 确保元素有基础动画类
        if (!element.classList.contains('animate')) {
            element.classList.add('animate');
        }
        observer.observe(element);
    });
    
    return observer;
}

/**
 * 添加点击波纹效果
 * @param {HTMLElement} element - 要添加波纹效果的元素
 * @param {Event} event - 点击事件对象
 */
export function addRippleEffect(element, event) {
    // 确保元素有相对定位
    if (window.getComputedStyle(element).position !== 'relative') {
        element.style.position = 'relative';
    }
    
    // 创建波纹元素
    const ripple = document.createElement('span');
    const rect = element.getBoundingClientRect();
    const size = Math.max(rect.width, rect.height);
    const x = event.clientX - rect.left - size / 2;
    const y = event.clientY - rect.top - size / 2;
    
    // 设置波纹样式
    ripple.style.width = ripple.style.height = size + 'px';
    ripple.style.left = x + 'px';
    ripple.style.top = y + 'px';
    ripple.classList.add('ripple');
    
    // 创建动画
    const rippleAnimation = ripple.animate([
        { transform: 'scale(0)', opacity: 0.5 },
        { transform: 'scale(1)', opacity: 0 }
    ], {
        duration: 600,
        easing: 'ease-out'
    });
    
    // 添加波纹到元素
    element.appendChild(ripple);
    
    // 动画结束后移除元素
    rippleAnimation.onfinish = () => {
        ripple.remove();
    };
}

/**
 * 添加波纹效果样式到页面
 */
export function addRippleStyles() {
    // 检查是否已经添加过波纹样式
    if (document.querySelector('style[data-ripple]')) {
        return;
    }
    
    const style = document.createElement('style');
    style.setAttribute('data-ripple', 'true');
    style.textContent = `
        .ripple {
            position: absolute;
            border-radius: 50%;
            background-color: rgba(102, 126, 234, 0.3);
            transform: scale(0);
            pointer-events: none;
            z-index: 3;
        }
        
        .ripple-dark {
            background-color: rgba(255, 255, 255, 0.3);
        }
    `;
    document.head.appendChild(style);
}

/**
 * 显示全局加载指示器
 * @param {string} message - 加载消息
 * @returns {HTMLElement} - 加载指示器元素
 */
export function showLoadingIndicator(message = '加载中...') {
    // 检查是否已经有加载指示器
    let loader = document.querySelector('.global-loader');
    
    if (loader) {
        // 更新消息
        const loaderText = loader.querySelector('.loader-text');
        if (loaderText) {
            loaderText.textContent = message;
        }
        return loader;
    }
    
    // 创建加载指示器
    loader = document.createElement('div');
    loader.className = 'global-loader';
    loader.innerHTML = `
        <div class="loader-content">
            <div class="loader-spinner"></div>
            <p class="loader-text">${message}</p>
        </div>
    `;
    
    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
        .global-loader {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            transition: opacity 0.3s ease;
        }
        
        .global-loader.dark {
            background-color: rgba(0, 0, 0, 0.9);
        }
        
        .global-loader.fade-out {
            opacity: 0;
        }
        
        .loader-content {
            text-align: center;
            padding: 2rem;
            border-radius: 1rem;
            background-color: white;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        }
        
        .dark .loader-content {
            background-color: #1e293b;
        }
        
        .loader-spinner {
            width: 50px;
            height: 50px;
            border: 3px solid rgba(102, 126, 234, 0.3);
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }
        
        .loader-text {
            color: var(--color-text-secondary, #64748b);
            font-size: 1rem;
            margin: 0;
        }
        
        .dark .loader-text {
            color: var(--color-text-light, #e2e8f0);
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);
    
    // 添加到页面
    document.body.appendChild(loader);
    document.body.style.overflow = 'hidden';
    
    return loader;
}

/**
 * 隐藏全局加载指示器
 * @param {Function} callback - 完全隐藏后的回调函数
 */
export function hideLoadingIndicator(callback) {
    const loader = document.querySelector('.global-loader');
    
    if (!loader) {
        if (callback) callback();
        return;
    }
    
    // 添加淡出动画
    loader.classList.add('fade-out');
    
    // 动画结束后移除
    setTimeout(() => {
        if (loader.parentNode) {
            loader.parentNode.removeChild(loader);
        }
        document.body.style.overflow = '';
        
        if (callback) callback();
    }, 300);
}

/**
 * 页面元素进入动画
 * @param {HTMLElement} element - 要添加动画的元素
 * @param {string} animation - 动画类型
 * @param {number} delay - 延迟时间（毫秒）
 */
export function animateElement(element, animation = 'fade-in', delay = 0) {
    if (!element) return;
    
    // 添加动画类和样式
    element.style.opacity = '0';
    
    switch (animation) {
        case 'fade-in':
            element.style.transform = 'translateY(0)';
            break;
        case 'slide-up':
            element.style.transform = 'translateY(20px)';
            break;
        case 'slide-down':
            element.style.transform = 'translateY(-20px)';
            break;
        case 'slide-left':
            element.style.transform = 'translateX(20px)';
            break;
        case 'slide-right':
            element.style.transform = 'translateX(-20px)';
            break;
        case 'zoom-in':
            element.style.transform = 'scale(0.95)';
            break;
    }
    
    // 设置过渡
    element.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    
    // 应用动画
    setTimeout(() => {
        element.style.opacity = '1';
        element.style.transform = 'none';
    }, delay);
}

/**
 * 为页面添加页面加载动画
 */
export function addPageLoadAnimations() {
    // 为页面元素添加动画类
    const animatedElements = document.querySelectorAll(
        '.animate-on-scroll, .fade-in, .slide-up, .zoom-in'
    );
    
    animatedElements.forEach((element, index) => {
        // 延迟动画，创建级联效果
        const delay = index * 50;
        animateElement(element, element.dataset.animation || 'fade-in', delay);
    });
}